package com.itheima.gatewaymedia.filters;

import com.itheima.common.constants.SystemConstants;
import com.itheima.common.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @version 1.0
 * @description 自媒体管理系统 统一登录鉴权
 * @package com.itheima.gatewayadmin.filters
 */
@Component
@Slf4j
public class WemediaAuthorizeFilter implements GlobalFilter, Ordered {
    /**
     * 统一鉴权
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //0. 获取请求与响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 获取请求路径
        String path = request.getURI().getPath();
        // 如果是登录请求地址要放行  /wemedia/login/in
        log.info("请求了路径:" + path);
        if(path.startsWith("/wemedia/login")){
            try {
                return chain.filter(exchange);
            }catch (Throwable e){
                e.printStackTrace();
            }
        }
        //1. 从请求头获取token
        String token = request.getHeaders().getFirst("token");
        //2. 有值，验证有效期
        if(StringUtils.isNotEmpty(token)){
            int verifyToken = AppJwtUtil.verifyToken(token);
            // 判断校验结果，如果是ok，则放行
            if(SystemConstants.JWT_OK == verifyToken){
                // 获取载荷
                Claims claims = AppJwtUtil.getClaimsBody(token);
                // 取出载荷中创建token时，存入的登录用户的id
                Integer loginUserId = (Integer) claims.get("id");
                // 给请求头添加一个字段：userId=loginUserId
                // 将来在转发的微服中就可以通过请求头来获取这个登录的用户id
                request.mutate().header(SystemConstants.USER_HEADER_NAME,loginUserId.toString());
                return chain.filter(exchange);
            }
        }
        //3. token没值, 返回401
        //4. 失效 返回401
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
